package controllers;

import com.alibaba.fastjson.JSONObject;
import jobs.BaseJob;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import play.mvc.Controller;
import utils.xtask.XTaskService;
import xtask.XTaskBean;
import utils.BeanUtils;

import java.util.List;

/**
 * @author zhangzc
 * @since 5/18/18
 */
public class XTasks extends BaseCommonController {

    public static void listTask(){
        List<Class> classList = Play.classloader.getAssignableClasses(BaseJob.class);
        List<XTaskBean> taskList = BeanUtils.buildList(XTaskBean.class, classList);
        render(taskList);
    }

    public static void viewTask(String jobName){
        List<JSONObject> logs = XTaskService.getLogList(jobName);
        render(logs);
    }

    public static void executeTask(String jobName){
        List<Class> classList = Play.classloader.getAssignableClasses(BaseJob.class);
        String errorMsg = "无法找到任务";
        for(Class c: classList){
            if(StringUtils.equalsIgnoreCase(jobName, c.getName())){
                try {
                    BaseJob job = (BaseJob) c.newInstance();
                    job.now();
                    errorMsg = null;
                } catch (Exception e) {
                    Logger.error(e, "Error in XTasks.executeTask(%s)", jobName);
                    errorMsg = "无法初始化任务对象！";
                }
                break;
            }
        }
        render(jobName, errorMsg);
    }
}
